/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
 var swapNodes = function(head, k) {

    
/*
    let temp = null;
    let fast = head;
    let slow = head;
    for(let i = 0;i < k-1;i++){
        fast = fast.next;
    }
    temp = fast;
    //console.log(fast);
    while(fast.next != null) {
        fast = fast.next;
        slow = slow.next;
    }
    console.log(temp.val);
    console.log(slow.val);
    slow.val = temp.val;
*/
    //节点已经找到，但是无法交换了

    let dummy = new ListNode(0)  //初始化，使快慢指针的next可以指向head的第一个元素
    dummy.next = head;
    let i = 0, cur = dummy;
    let slow = dummy, fast =dummy;

    while(i++ < k){
        fast = fast.next;
        cur = cur.next;
    }

    while(fast){
        fast = fast.next;
        slow = slow.next;
    }

    let temp = cur.val;
    cur.val = slow.val;
    slow.val = temp;

    return head;
};
